<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="入库编号" prop="warehouseInNo">
        <el-input v-model="queryParams.warehouseInNo" placeholder="请输入入库编号" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="状态" prop="goodsType">
        <el-select v-model="queryParams.warehouseInStatus" placeholder="请选择状态" clearable style="width: 180px">
          <el-option v-for="dict in warehouse_in_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['stock:in:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['stock:in:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inList">
      <el-table-column label="入库编号" align="center" prop="warehouseInNo" width="210">
        <template #default="scope">
          <span @click="handleShowDetails(scope.row)" style="color: #1c84c6">{{scope.row.warehouseInNo}}</span>
        </template>
      </el-table-column>
      <el-table-column label="来源" align="center" prop="sourceNo" />
      <el-table-column label="入库类型" align="center" prop="goodsType">
        <template #default="scope">
          <dict-tag :options="warehouse_in_store_type" :value="scope.row.goodsType"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="warehouseInStatus">
        <template #default="scope">
          <dict-tag :options="warehouse_in_type" :value="scope.row.warehouseInStatus"/>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList"/>
    <!-- 添加或修改入库对话框 -->
    <el-dialog :title="title" v-model="open" style="width: 70%; height: 80%" append-to-body>
      <el-form ref="inRef" :model="form" :rules="rules" label-width="80px">
        <div style="display: flex;justify-content: space-between;">
        <el-form-item label="入库编号">
          <el-input v-model="form.warehouseInNo" placeholder="请输入入库编号" disabled/>
        </el-form-item>
        <el-form-item label="来源编号" prop="sourceNo">
          <el-select v-model="form.sourceNo" placeholder="请选择申请编号" style="width: 240px">
            <el-option v-for="option in selectOrderOptions" :key="option.value" :label="option.label" :value="option.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="入库类型" prop="goodsType">
          <el-select v-model="form.goodsType" placeholder="请选择入库类型" style="width: 180px">
            <el-option
                v-for="dict in warehouse_in_store_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        </div>
        <div>
          <h2>采购入库清单</h2>
          <el-col :span="1.5" class="mb8">
            <el-button type="primary" plain icon="Plus" @click="handleAddMaterial">新增</el-button>
          </el-col>
          <el-table  style="height: 300px; overflow: auto;" :data="warehouseInInfoList">
            <el-table-column label="物料名称" align="center" prop="goodsNo" >
              <template #default="scope">
                <el-select
                    v-model="scope.row.goodsNo"
                    placeholder="Select"
                    size="large"
                    style="width: 240px"
                >
                  <el-option v-for="option in selectMaterialOptions" :key="option.value" :label="option.label" :value="option.value"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="数量" align="center" prop="warehouseInNumber" >
              <template #default="scope">
                <el-input-number min="1" v-model="scope.row.warehouseInNumber"></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--  采购订单详情页  -->
    <el-dialog :title="title" v-model="openA" style="width: 70%; height: 80%" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" >
        <div style="display: flex;justify-content: space-between;">
          <el-form-item label="入库编号" >
            <el-input v-model="form.warehouseInNo" disabled style="width: 210px" />
          </el-form-item>
          <el-form-item label="采购订单编号" >
            <el-input v-model="form.sourceNo" disabled style="width: 210px" />
          </el-form-item>
          <el-form-item label="入库类型">
            <el-select v-model="form.goodsType" placeholder="请选择入库类型" style="width: 180px" disabled>
              <el-option
                  v-for="dict in warehouse_in_store_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div>
          <h2>采购入库清单</h2>
          <el-table  style="height: 380px; overflow: auto;" :data="warehouseInInfoList">
            <el-table-column label="物料编号" align="center" prop="goodsNo" />
            <el-table-column label="物料名称" align="center" prop="materialName" />
            <el-table-column label="数量" align="center" prop="warehouseInNumber" />
            <el-table-column label="单位" align="center" prop="unitId">
              <template #default="scope">
                <dict-tag :options="unit_type" :value="scope.row.unitId" />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="In">
import { listIn, getIn, delIn, addIn, updateIn, getCGRK, addPurchase } from "@/api/purchase/warehouse";
import {updateOrder, listOrder} from "../../../api/purchase/order.js";
import {listMaterials} from "../../../api/base/materials.js";
import {changeStatus} from "../../../api/purchase/apply/apply.js";

const { proxy } = getCurrentInstance();
const { warehouse_in_store_type, warehouse_in_type,unit_type } = proxy.useDict('warehouse_in_store_type', 'warehouse_in_type','unit_type');

const inList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const openA = ref(false);

const data = reactive({
  form: {
    warehouseInInfoList:[]
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    warehouseInNo: null,
    sourceNo: null,
    goodsType: null,
    warehouseInStatus: null,
    warehouseInDate: null,
    userId: null
  },
  rules: {
    warehouseInNo: [
      { required: true, message: "入库编号不能为空", trigger: "change" }
    ],
    sourceNo: [
      { required: true, message: "来源不能为空", trigger: "blur" }
    ],
    goodsType: [
      { required: true, message: "入库类型不能为空", trigger: "change" }
    ],
    warehouseInStatus: [
      { required: true, message: "入库状态", trigger: "change" }
    ],
  }
});

//采购入库清单列表
const warehouseInInfoList = ref([])
const { queryParams, form, rules } = toRefs(data);

/** 查询入库列表 */
function getList() {
  loading.value = true;
  // 修改查询参数，添加 type 为 1 的条件
  const updatedQueryParams = {...queryParams.value, goodsType: 1 };
  listIn(updatedQueryParams).then(response => {
    inList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    warehouseInNo: null,
    sourceNo: null,
    goodsType: null,
    warehouseInStatus: null,
    warehouseInDate: null,
    userId: null
  };
  proxy.resetForm("inRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

const orderList = ref([]);
const materialsList = ref([]);

// 获取采购申请单列表
const getOrderList = async () => {
  const response = await listOrder({ status: 2 });
  orderList.value = response.rows;
  // console.log(orderList.value)
};
/** 查询物料管理列表 */
const getMaterialList = async () =>  {
  const response = await listMaterials();
  materialsList.value = response.rows
  // console.log(materialsList.value)
}
// 在页面加载时获取用户列表、物料列表
onMounted(() => {
  getOrderList();
  getMaterialList();
});

const selectOrderOptions = computed(() => {
  return orderList.value.map(purchaseOrder => ({ label: purchaseOrder.purchaseOrderNo, value: purchaseOrder.purchaseOrderNo }));
});
const selectMaterialOptions = computed(() => {
  return materialsList.value.map(material => ({ label: material.materialName, value: material.materialNo}));
});
// 新增采购入库清单
function handleAddMaterial(){
  let obj = {
    materialId: '',
    warehouseInNumber: ''
  }
  warehouseInInfoList.value.push(obj);
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  warehouseInInfoList.value = []
  form.value.warehouseInInfoList = warehouseInInfoList;
  getCGRK().then(response => {
    form.value.warehouseInNo= response.msg
  })
  open.value = true;
  title.value = "添加入库";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getIn(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改入库";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["inRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateIn(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPurchase(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
          const purchaseOrderNo = form.value.sourceNo;
          // console.log(purchaseOrderNo);
          listOrder({purchaseOrderNo:purchaseOrderNo}).then(response => {
            if (response && response.rows && response.rows.length > 0) {
              const orderId = response.rows[0].id; // 假设返回数据结构中订单ID在rows数组的对象中
              const applyId = response.rows[0].purchaseApplyId;
              // console.log('订单的id值为:', orderId);
              // console.log('申请的的id值为:', applyId)
              const updatedOrder = {
                id: orderId,
                status: 4,
                orderDate: new Date(), // 设置实际到货时间为当前时间
                purchaseOrderMaterials: response.rows[0].purchaseOrderMaterials,
              };
              updateOrder(updatedOrder).then(() => {
                changeStatus(applyId, 5).then(() => {
                }).catch(error => {
                });
              }).catch(error => {
              });
            }
          })
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除入库编号为"' + _ids + '"的数据项？').then(function() {
    return delIn(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('stock/in/export', {
    ...queryParams.value
  }, `in_${new Date().getTime()}.xlsx`)
}

// 显示详情页
function handleShowDetails(row) {
  form.value = {...row };
  warehouseInInfoList.value = row.warehouseInInfoList || [];
  openA.value = true;
  title.value = "采购入库详情";
}

getList();
</script>
